/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {StyleSheet, Text, View, Dimensions, Modal, TouchableOpacity, PixelRatio, TouchableHighlight, Image, NativeModules, ScrollView, Platform, BackHandler, DeviceEventEmitter} from 'react-native';

import LinearGradient from 'react-native-linear-gradient';

import Toast from 'react-native-root-toast';

import Common from '../../component/common';

import ToolbarComponent from '../../component/ToolbarComponent';

import Loading from '../../component/loading';

import LoadError from '../../component/loadError';

import PayResult from './payResult';

import AppStorage from '../../component/appstorage';

const totalWidth = Dimensions.get('window').width;

const os = Platform.OS;

export default class Recharge extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      success: true,
      isAlipay: false,
      isWeChat: true,
      isBankCard: false,
      payWay: "wechatPay",
      checkDevice: '',
      wechat: true,
      balance: 0,
      selected: false,
      selected0: true,
      coinList: [],
      price: 0,
      modalVisible: false,
    };
  }

  componentWillMount(){
    Common.checkDevice((checkDevice) => {
      this.setState({checkDevice});
    });
    if( os === 'ios'){
      NativeModules.JsAndroid.checkThirdStatus((e) => {
        this.setState({
          wechat: e.wechat,
        });
      });
      // this.setState({balance: loginInfo.coinIos});
    }
    if (os === 'android') {
      BackHandler.addEventListener('hardwareBackPress', () => Common.onBack(this));
      // this.setState({balance: loginInfo.coinAnd});
    }
     this.finishPay=DeviceEventEmitter.addListener('finishPay', (e)=>{
       if(e.status == "true"){
         Common.onForward(this, PayResult, e.status, this.entity, "", "yes");
         DeviceEventEmitter.emit('successPay',null);
       }else{
         Common.onForward(this, PayResult, e.status, this.entity, "", "yes");
       }
     });
  }
  componentDidMount(){
    // this.fetchSpecialColumnPay();
    this.fetchCoinList();
    this.fetchBalance();

  }
  fetchBalance = () => {
    let formData = new FormData();
    formData.append("userToken",loginInfo.userToken);
    Common.fetchData("post", "/userCenter/balanceInquiry", formData, (responseData) => {
      if (os === 'ios') {
        this.setState({
          balance: responseData.entity[0].coinIos
        });
      }else{
        this.setState({
          balance: responseData.entity[0].coinAnd
        });
      }
    },() => {
      console.log('error');
    },() => {
      console.log('error');
    });
  };
  fetchCoinList = () => {
    let formData = new FormData();
    if(this.props.name){
      formData.append("productId",this.props.name);
      formData.append("userToken",loginInfo.userToken);
      formData.append("deviceType", os == "ios"?1:2);
      Common.fetchData("post", "/unionPay/purchasesc", formData, (responseData) => {
        this.setState({
          price: responseData.entity[0].coinList[0].price,
          coinList: responseData.entity[0].coinList
        });
        },() => {
          console.log('error');
        },() => {
          console.log('error');
        });
    }else{
      Common.fetchData("post", "/unionPay/coinlist", formData, (responseData) => {
        this.setState({
          price: responseData.entity[0].coinList[0].price,
          coinList: responseData.entity[0].coinList
        });
        },() => {
          console.log('error');
        },() => {
          console.log('error');
        });
    }
  }
  // fetchSpecialColumnPay = () => {
  //   this.setState({
  //     loading: true,
  //     success: false,
  //   });
  //   let formData = new FormData();
  //   // formData.append('entityId','ff8080815c496fcf015c4970c8430053');
  //   // formData.append('entityType',8);
  //   // formData.append('userToken',"582b73e10347b0eececdbaf131916af0");
  //   formData.append('entityId',this.props.did);
  //   formData.append('entityType',this.props.name);
  //   formData.append('userToken',loginInfo.userToken);
  //   Common.fetchData("post", "/buyHistory/getBuy", formData, (responseData) => {
  //     this.entity = responseData.entity;
  //     this.setState({loading: false,
  //                     success: true,
  //                   });
  //     },() => {
  //       this.setState({loading: false,
  //                       success: false,
  //                       errorMessage: "请求失败",
  //                     });
  //     },() => {
  //       this.setState({loading: false,
  //                       success: false,
  //                       errorMessage: "网络错误",
  //                     });
  //   });
  // }
  componentWillUnmount() {
    if (os === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', () => Common.onBack(this));
    }
     this.finishPay.remove();
  }
  selectPayWay = (type) => {
      if(this.state.wechat){
        this.setState({payWay: type});
        switch (type){
          case "alipay":
            this.setState({
              isAlipay: true,
              isWeChat: false,
              isBankCard: false});
            break;
          case "wechatPay":
            this.setState({
              isAlipay: false,
              isWeChat: true,
              isBankCard: false});
            break;
          case "bankcard":
            this.setState({
              isAlipay: false,
              isWeChat: false,
              isBankCard: true});
            break;
        }
      }else{
        Toast.show("请您先安装微信再进行支付", {
          duration: Toast.durations.LONG,
          position: Toast.positions.CENTER,
          shadow: true,
          animation: true,
          hideOnPress: true,
          delay: 0});
      }
  };
  payment = (url) => {
    let formData = new FormData();
    if(this.props.name){
      formData.append("productId",this.props.name);
    }
    formData.append("userToken",loginInfo.userToken);
    formData.append("amount",this.state.price);
    Common.fetchData("post", url, formData, (responseData) => {
      if(responseData.entity[0].status == "success"){
        DeviceEventEmitter.emit('successPay',null);
        Common.onForward(this,PayResult,"true",this.props.did,"","yes");
        loginInfo.coinAnd = responseData.entity[0].coinAnd;
        loginInfo.coinIos = responseData.entity[0].coinIos;
        AppStorage._updataLocalData("login", loginInfo);
      }else{
        Common.onForward(this,PayResult,"false",this.props.did,"","yes");
      }
    },() => {
      console.log('error');
      Common.onForward(this,PayResult,"false",this.props.did,"","yes");
    },() => {
      console.log('error');
      Common.onForward(this,PayResult,"false",this.props.did,"","yes");
    });
  };
  confirmPay = () => {    
    // if(this.state.isAlipay || this.state.isWeChat || this.state.isBankCard){
    // if(this.state.wechat){
    //   // this.state.payWay;   支付方式
    //   // this.props.did;      专栏id
    //   // this.props.name      商品类型(现在只是专栏)
    //   NativeModules.JsAndroid.confirmPay(this.state.payWay, this.props.name, this.props.did, loginInfo.userToken);
    // }else{
    //   Toast.show("至少选择一种支付方式", {
    //     duration: Toast.durations.LONG,
    //     position: Toast.positions.CENTER,
    //     shadow: true,
    //     animation: true,
    //     hideOnPress: true,
    //     delay: 0});
    // }
    if(os == 'ios'){
      NativeModules.JsAndroid.riseIap(this.state.price);
      this.setState({modalVisible:true});
      this.finishIap=DeviceEventEmitter.addListener('finishIap', (e)=>{
        if(e.status){
          this.payment("/unionPay/topupios");
        }else{
          Common.onForward(this,PayResult,"false",this.props.did,"","yes");
        }
        this.setState({modalVisible: false});
      });
    }else{
      if(this.state.isAlipay || this.state.isWeChat || this.state.isBankCard){
        NativeModules.JsAndroid.confirmPay(this.state.payWay, this.state.price, loginInfo.userToken, this.props.name);
      }
    }
  };
  selectedCoin = (price,idx) => {
    this.setState({price});
    switch (idx){
      case 0:
         this.setState({
          'selected0': true,
          'selected1': false,
          'selected2': false,
          'selected3': false,
          'selected4': false,
          'selected5': false,
         });
         break;
       case 1:
         this.setState({
          'selected0': false,
          'selected1': true,
          'selected2': false,
          'selected3': false,
          'selected4': false,
          'selected5': false,
         });
         break;
        case 2:
          this.setState({
          'selected0': false,
          'selected1': false,
          'selected2': true,
          'selected3': false,
          'selected4': false,
          'selected5': false,
         });
         break;
        case 3:
          this.setState({
          'selected0': false,
          'selected1': false,
          'selected2': false,
          'selected3': true,
          'selected4': false,
          'selected5': false,
         });
         break;
         case 4:
          this.setState({
          'selected0': false,
          'selected1': false,
          'selected2': false,
          'selected3': false,
          'selected4': true,
          'selected5': false,
         });
         break;
         case 5:
          this.setState({
          'selected0': false,
          'selected1': false,
          'selected2': false,
          'selected3': false,
          'selected4': false,
          'selected5': true,
         });
         break;
    }
    // this.setState({'selected2':true});
  };
  render(){
    var note = "";
    if( os === 'ios'){
      note = "1.因Apple政策原因，充值仅支持指定价格；\n2.余额仅限IOS消费，无法跨平台使用，不可提现、转赠。";
    }else if(os === 'android'){
      note = "余额仅限Android消费，无法跨平台使用，不可提现、转赠。";
    }
    return (
      <View style={styles.container}>
        <ToolbarComponent
          leftItem={{
            title: 'Back',
            layout: 'icon',
            icon: require("../../images/back.png"),
            onPress: () => {
              Common.onBack(this);
            },
          }}
        >
          <View style={styles.toolbarV}>
            <Text style={styles.toolbarT} numberOfLines={1}>我的账户</Text>
          </View>
        </ToolbarComponent>
        {
        this.state.loading?
          <Loading />:
          (this.state.success?
            <View style={{flex: 1}}>
              <ScrollView style={{flex: 1}}>
                {/*<View style={styles.subscribeBox}>
                  <View style={styles.subscribeLeftBox}>
                    <Text style={styles.subscribeLabel}>{this.entity.typeName}</Text>
                    <Text style={styles.subscribeTitle}>{this.entity.specialColumnTitle}</Text>
                    <Text style={styles.subscribeLabel}>主讲人：{this.entity.userName}</Text>
                    <Text style={styles.subscribeLabel}>共{this.entity.totalColumnNumber}期</Text>
                  </View>
                  {this.entity.specialColumnPic1?
                    <Image style={styles.subscribeImg} source={{uri: this.entity.specialColumnPic1}}/>:
                    <View style={[styles.subscribeImg,{borderColor: '#ededed', borderWidth: 1/PixelRatio.get()}]}>
                      <Text style={{color: '#ededed',fontSize: 12}}>暂无图片</Text>
                    </View>
                  }
                </View>*/}
                <View style={styles.subscribePay}>
                  <View style={styles.balanceMoney}>
                    <Text style={styles.balanceMoneyCon}>余额 <Text style={{fontSize: 32,color: '#fe4543'}}>{this.state.balance}</Text></Text>
                    <Image style={styles.balanceMoneyIcon} source={require('../../images/pay/yue.png')} />
                  </View>
                  <View style={styles.rechargeMoney}>
                    <Text style={styles.rechargeMoneyTitle}>余额充值</Text>
                    <View style={styles.rechargeMoneyCon}>
                      
                      <View style={styles.rechargeMoneyRow}>
                        {
                          this.state.coinList.map((val,idx) => {
                            return (
                              <TouchableOpacity key={idx} style={styles.rechargeMoneyConW} onPress={() => {this.selectedCoin(val.price,idx)}}>
                                <View style={styles.rechargeMoneyIconW}>
                                  {
                                    this.state['selected'+idx]?
                                  <Image style={styles.rechargeMoneyIcon} source={require('../../images/pay/check2.png')} />:null
                                  }
                                </View>
                                <Text style={[styles.rechargeMoneyLabel,this.state['selected'+idx]?{color: '#fe4543'}:null]}>{val.price}元</Text>
                              </TouchableOpacity>
                            )
                          })
                        }
                      </View>
                    </View>
                  </View>
                  <View style={styles.subscribeMoney}>
                    <Text style={styles.subscribeMoneyLabel}>需支付</Text>
                    <Text style={styles.subscribeMoneyNumber}>¥<Text style={styles.subscribeMoneyNumberT}>{this.state.price}</Text></Text>
                  </View>
                  {
                    os === "android"?
                      <TouchableHighlight underlayColor="#fafafa" onPress={() => {this.selectPayWay("wechatPay")}}>
                      <View style={styles.payWay}>
                        <View style={{flexDirection: 'row',alignItems: 'center'}}>
                          <Image style={styles.payWayIcon} source={require('../../images/pay/wechatpay.png')} />
                          <Text style={styles.payWayLabel}>微信支付</Text>
                        </View>
                        {
                          this.state.isWeChat?<Image style={styles.selectedIcon} source={require('../../images/pay/check.png')} />:null
                        }
                      </View>
                    </TouchableHighlight>:null
                  }
                  
                  {/*
                  <TouchableHighlight underlayColor="#fafafa" onPress={() => {this.selectPayWay("alipay")}}>
                    <View style={styles.payWay}>
                      <View style={{flexDirection: 'row',alignItems: 'center'}}>
                        <Image style={styles.payWayIcon} source={require('../../images/pay/alipay.png')} />
                        <Text style={styles.payWayLabel}>支付宝支付</Text>
                      </View>
                      {
                        this.state.isAlipay?<Image style={styles.selectedIcon} source={require('../../images/pay/check.png')} />:null
                      }
                    </View>
                  </TouchableHighlight>
                */}
                {/*
                  <TouchableHighlight underlayColor="#ececec" onPress={() => {this.selectPayWay("bankcard")}}>
                    <View style={styles.payWay}>
                      <View style={{flexDirection: 'row',alignItems: 'center'}}>
                        <Image style={styles.payWayIcon} source={require('../../images/pay/bankcard.png')} />
                        <Text style={styles.payWayLabel}>银行卡支付</Text>
                      </View>
                      {
                        this.state.isBankCard?<Image style={styles.selectedIcon} source={require('../../images/pay/check.png')} />:null
                      }
                    </View>
                  </TouchableHighlight>
                  {
                    this.state.isBankCard?
                    <View>
                      <TouchableHighlight>
                        <View style={styles.payWay}>
                          <Text style={styles.payWayLabel}>招商银行储蓄卡（0000）</Text>
                          <Image style={styles.selectedIcon} source={require('../../images/pay/next.png')} />
                        </View>
                      </TouchableHighlight>
                      </View>:null
                  }
                  */}
                </View>
                <View style={styles.note}>
                  <Text style={styles.noteText}>{note}</Text>
                </View>
              </ScrollView>
              <View>
                <LinearGradient colors={['rgba(0,0,0, 0)', 'rgba(19,19,19,0.03)']} style={{width: totalWidth,height: totalWidth*0.015}} />
                <TouchableOpacity style={[styles.bottom,this.state.checkDevice == 'x'?{paddingBottom: totalWidth*0.05}:null]} onPress = {this.confirmPay}>
                  <Text style={styles.bottomT}>确认支付</Text>
                </TouchableOpacity>
              </View>
              {
                this.state.modalVisible?
                  <Modal animationType={"fade"}
                      transparent={true}
                      visible={this.state.modalVisible}
                      onRequestClose={this.isShow}>
                      <TouchableOpacity style={styles.mask} onPress={this.isShow}>
                        <Loading bgStyle={styles.cirLoading}/>
                      </TouchableOpacity>
                    </Modal>:null
                }
            </View>
            :<LoadError reload={this.fetchSpecialColumnData} reason={this.state.errorMessage}/>
          ) 
        }
        
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f4f4f4',
  },
  toolbarV: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  toolbarT: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 20
  },
  subscribeBox: {
    backgroundColor: '#fff',
    marginVertical: totalWidth*0.036,
    paddingVertical: totalWidth*0.032,
    paddingHorizontal: totalWidth*0.0532,
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  subscribeLeftBox: {
    flex: 1,
    justifyContent: 'center'
  },
  subscribeLabel: {
    color: '#000',
    fontSize: 12,
    lineHeight: Math.round(totalWidth*0.053),
  },
  subscribeTitle: {
    color: '#000',
    fontSize: 16,
    fontWeight: 'bold',
    marginVertical: totalWidth*0.01,
  },

  subscribeImg: {
    width: totalWidth*0.2,
    height: totalWidth*0.26,
    alignItems: 'center',
    justifyContent: 'center',
  },
  subscribePay: {
    backgroundColor: '#f6f6f6',
  },
  balanceMoney: {
    backgroundColor: '#ffffff',
    paddingVertical: totalWidth*0.048,
    marginVertical: totalWidth*0.04,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  balanceMoneyCon: {
    fontSize: 28,
  },
  balanceMoneyIcon: {
    width: totalWidth*0.04,
    height: totalWidth*0.04,
    resizeMode: 'contain',
    alignSelf: 'flex-end',
    marginBottom: totalWidth*0.013,
    marginLeft: totalWidth*0.013,
  },
  rechargeMoney: {
    backgroundColor: '#ffffff',
  },
  rechargeMoneyTitle: {
    color: '#585858',
    fontSize: 12,
    paddingHorizontal: totalWidth*0.064,
    paddingTop: totalWidth*0.04,
  },
  rechargeMoneyCon: {
    padding: totalWidth*0.04,
    borderBottomWidth: 1/PixelRatio.get(),
    borderBottomColor: '#f3f3f3',
  },
  rechargeMoneyRow: {
    flexWrap: 'wrap',
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  rechargeMoneyConW: {
    width: totalWidth*0.3,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: totalWidth*0.02,
  },
  rechargeMoneyIconW: {
    flex: 1,
    marginRight: totalWidth*0.02,
    alignItems: 'flex-end',
  },
  rechargeMoneyIcon: {
    
    width: totalWidth*0.032,
    height: totalWidth*0.026,
    resizeMode: 'contain',
  },
  rechargeMoneyLabel: {
    flex: 2,
    color: '#a1a1a1',
    fontSize: 18,
  },
  subscribeMoney: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: totalWidth*0.064,
    height: totalWidth*0.207,
    alignItems: 'center',
    borderBottomWidth: 2/PixelRatio.get(),
    borderColor: '#eeedf2',
    backgroundColor: '#ffffff',
  },
  subscribeMoneyLabel: {
    color: '#000',
    fontSize: 16,
  },
  subscribeMoneyNumber: {
    color: '#ff4544',
    fontSize: 18,
  },
  subscribeMoneyNumberT: {
    fontSize: 22,
  },
  payWay: {
    paddingHorizontal: totalWidth*0.037,
    backgroundColor: '#ffffff',
    flexDirection: 'row',
    height: totalWidth*0.141,
    alignItems: 'center',
    borderColor: '#f5f5f5',
    borderBottomWidth: 1/PixelRatio.get(),
    justifyContent: 'space-between',
  },
  payWayIcon: {
    width: totalWidth*0.067,
    height: totalWidth*0.067,
    resizeMode: 'contain', 
  },
  payWayLabel: {
    marginLeft: 5,
    color: '#4b525c',
    fontSize: 12,

  },
  selectedIcon: {
    width: totalWidth*0.026,
    height: totalWidth*0.04,
    resizeMode: 'contain',
  },
  note: {
    paddingHorizontal: totalWidth*0.05,
    paddingVertical: totalWidth*0.026,
  },
  noteText: {
    color: '#656565',
    fontSize: 13,
    lineHeight: Math.round(totalWidth*0.045),
  },
  bottom: {
    backgroundColor: '#fff',
    height: totalWidth*0.148,
    justifyContent: 'center',
    alignItems: 'center',
  },
  bottomT: {
    color: '#ff4546',
    fontSize: 16,
  },
  mask: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(0,0,0,0.5)',
  },
  cirLoading: {flex: 0,width: totalWidth*0.42,height: totalWidth*0.25,borderRadius: 5}
});